const app = getApp();
let timesWS = 0, socketMsgQueue = [], allCharArr = [];
Page({

    /**
     * 页面的初始数据
     */
    data: {
        loading: app.globalData.loading,
        barTitle:"聊天室",
        InputBottom:0,
        page:1,
        chatArr:[],
        message:''
    },
    InputFocus(e) {
        this.setData({
            InputBottom: e.detail.height
        })
    },
    InputBlur(e) {
        this.setData({
            InputBottom: 0
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (op) {
        app.setAppSystem(this),
            app.userLogin(this);
        this.initData(op);
        this.setData({loading:false});
    },
    initData(op){
        this.setData({ user_id: wx.getStorageSync('users').id });
        this.getChat();
    },
    getChat(){
        let _this = this,
            arr = _this.data.chatArr,
            reset_arr = [],
            page = _this.data.page;
        app.hyy.request({
            url: "entry/wxapp/GetChatLog",
            cachetime: "0",
            data:{page:_this.data.page},
            success: function (res) {
                let res_d = res.data;
                if (res_d.length > 0){
                    _this.setData({ page: page+1 });
                    for (let i = 0; i < res_d.length; i++){
                        let parse = JSON.parse(res_d[i]);
                        reset_arr.push(parse);
                    }
                }
                _this.setData({
                    loading:false,
                    chatArr: reset_arr
                });
                _this.pageScrollToBottom();
            }

        });
    },
    sendMsg(e){ // 发送聊天信息
        let _this = this,
        chatArr = _this.data.chatArr,
        content = _this.data.message,
        datetime = new Date();
        if (content == '') {
            wx.showModal({
                title: '提示',
                content: '内容为空',
            })
            return;
        }
        let year = datetime.getFullYear(), month = datetime.getMonth(), curday = datetime.getDate(), getHours = datetime.getHours(), getMinutes = datetime.getMinutes(), getSeconds = datetime.getSeconds();
        let resData = {
            wc_type:"chat",
            chat_content:_this.data.message,
            chat_type:1,
            user_id: _this.data.user_id,
            img:wx.getStorageSync('users').img,
            create_time: year + '年' + month + '月' + curday + '日' + getHours + ':' + getMinutes + ':' + getSeconds,
            uniacid: wx.getStorageSync('uniacid')
        };

        chatArr.push(resData)
        _this.setData({
            chatArr: chatArr,
            message: ''
        });
        _this.pageScrollToBottom();

        // WS发送
        if(app.globalData.socketTask.readyState !== 1){
            wx.showModal({
                title: '提示',
                content: '服务连接失败，请重试！',
            })
            return;
        }
        wx.sendSocketMessage({
            data: JSON.stringify(resData)
        });
        
        // app.hyy.request({
        //     url: "entry/wxapp/saveChatMsg",
        //     data: resData,
        //     success: function (res) {
                
        //     }
        // });
        
    },
    getMsg(e){
        let val = e.detail.value;
        this.setData({
            message: val
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () { 
        
    },
    pageScrollToBottom: function () {
        wx.createSelectorQuery().select('#j_page').boundingClientRect(function (rect) {
            // 使页面滚动到底部
            wx.pageScrollTo({
                scrollTop: rect.height
            })
        }).exec()
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let _this = this;
        // 判断是否连接
        if (app.globalData.socketTask.readyState !== 1) {
            app.connectWS();
        }
        wx.onSocketMessage(function (res) {
            let data = JSON.parse(res.data);
            if (data.code == 1 && data.data.chat_content) {
                if(data.data.user_id == _this.data.user_id){
                    return;
                }
                let chatArr = _this.data.chatArr;
                chatArr.push(data.data);
                _this.setData({
                    chatArr: chatArr,
                    message: ''
                });
                wx.createSelectorQuery().select('#j_page').boundingClientRect(function (rect) {
                    let curHeight = wx.getSystemInfoSync().windowHeight;
                    if (rect.bottom <= curHeight+449){
                        wx.pageScrollTo({
                            scrollTop: rect.height
                        })
                    }
                }).exec()

            } else {
                console.log(data);
            }
        });
        wx.onSocketError(function (res) {
            console.log('socket连接错误', res);
        });
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})